<template>
  <div class="day-report-import-container">

    <div class="photo-upload-box">
      <div class="photo-box">
        <img src="./id-scan.png" class="pic1"/>
        <input type="file" accept="image/*" capture="camera" class="upload-file" @change="changePhoto($event)"
               ref="inputImg"/>
      </div>
      <span class="tip1">拍照录入</span>
      <span class="tip2">无原件，可手动输入身份证信息</span>
    </div>

    <div class="bank-real-info">
      <div class="bank-real-name">
        <span class="title">姓名：</span>
        <div class="phone-con">
          <input type="text" class="phone-num" placeholder="请输入员工姓名" maxlength="5" v-model="userName"
                 @blur="inputBlur"/>
        </div>
      </div>

      <div class="bank-real-name">
        <span class="title">身份证号：</span>
        <div class="phone-con">
          <input type="text" class="phone-num" placeholder="请输入员工身份证号码" maxlength="18" v-model="userCert"
                 @blur="inputBlur"/>
        </div>
      </div>
      <div class="bank-real-name">
        <span class="title">民族：</span>
        <div class="phone-con">
          <input type="text" class="phone-num" placeholder="请输入民族" maxlength="18" v-model="nation"
                 @blur="inputBlur"/>
        </div>
      </div>
    </div>

    <div class="photo-scan-warp" v-show="photoShow">
      <div class="photo-scan-box">
        <img :src="bankPhoto" class="photo-scan" onclick="return false"/>
      </div>
      <span class="discern-scan">正在识别中...</span>
    </div>

    <div class="day-report-import-btn" v-show="hideBtn">
      <button type="button" class="import-end-btn" @click="completeImport">录入完成</button>
      <button type="button" class="import-continue-btn" @click="continueImport">继续录入</button>
    </div>

    <backpage @backPage="backPage"></backpage>

    <v-dialog v-model="modalVal" :content="content" type="default" @sure="confirmModal"></v-dialog>
  </div>
</template>

<script>
  import {getBase64, getNowFormatDate} from "../../../config/util";
  import {baseUrl} from "../../../config/env";
  import backpage from "../../../components/backpage";
  import dialog from "../../../components/dialog";

  export default {
    inject: ['reload'],
    data() {
      return {
        photoShow: false,
        bankPhoto: "",
        userSign: "",
        assessToken: "",
        userName: "",
        userCert: "",
        nation: "",
        modalVal: false,
        content: "",
        docmHeight: document.documentElement.clientHeight,//默认屏幕高度
        showHeight: document.documentElement.clientHeight,//实时屏幕高度
        hideBtn: true//显示或者隐藏
      }
    },
    created() {
      let base64 = require('js-base64').Base64;
      this.userSign = base64.decode(sessionStorage.getItem("success"));
      this.queryAccessToken();
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          this.showHeight = document.body.clientHeight;
        })()
      };
    },
    methods: {
      confirmModal() {
        this.userName = "";
        this.userCert = "";
        this.nation = "";
        this.$refs.inputImg.value = '';
        this.modalVal = false;
      },
      backPage() {
        this.$router.push("/dayreportlist");
      },
      inputBlur() {
        window.scrollTo(0, 0);
      },
      queryAccessToken() {//获取银行卡扫描token
        this.axios.post(baseUrl + "/userbank/get_bank_access_token?sgin=" + this.userSign).then((res) => {
          let resultObj = res.data;
          this.assessToken = this.$decruption(resultObj.data);
        })
      },
      changePhoto(e) {//显示图片
        if (e.target.files.length > 0) {
          getBase64(e.target, (url) => {
            this.bankPhoto = 'data:image/png;base64,' + url;
            this.photoShow = true;
            this.$refs.inputImg.value = '';
            e.target.value = '';
            this.$nextTick(() => {
              this.uploadBankPhoto();
            });
          })
        }
      },
      uploadBankPhoto() {//百度API识别
        this.$vux.loading.show({
          text: '加载中',
        });
        let image = this.bankPhoto.split(",")[1];
        let virValue = getNowFormatDate(this.userSign);
        let data = {
          "image": image,
          "id_card_side": "front",
          "accessToken": this.assessToken,
          "virValue": this.$encruption(virValue)
        };

        this.axios.post(baseUrl + "/userbank/scan?sgin=" + this.userSign + "&type=1", data).then((res) => {
          let certInfo = res.data;
          this.photoShow = false;
          this.bankPhoto = "";
          this.$vux.loading.hide();

          if (certInfo.code == 0) {
            certInfo = certInfo.data;
            if (certInfo.name.words == "" && certInfo.IdCard.words == "") {
              this.$vux.toast.text("扫描失败，请重新扫描！", "middle");
            } else {
              this.userName = certInfo.name.words;
              this.userCert = certInfo.IdCard.words;
              this.nation = certInfo.nation.words;
            }
          } else if (certInfo.code == 20055 || certInfo.code == 10000 || certInfo.code == 10002 || certInfo.code == 10004) {
            this.$vux.toast.text(certInfo.msg, "middle");
          } else {
            this.$vux.toast.text(certInfo.data.error_msg, "middle");
          }
        }).catch(() => {
          this.photoShow = false;
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      checkNameAndCertNum() {//校验姓名和身份证
        let reg1 = /^[\u2E80-\u9FFF]+$/;
        let reg2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9X])$/;
        if (this.userName == "" || this.userName == undefined || this.userName == null) {
          this.$vux.toast.text("请输入员工姓名", "middle");
          return;
        } else if (!reg1.test(this.userName)) {
          this.$vux.toast.text("请输入中文姓名", "middle");
          return;
        }
        if (this.userCert == "" || this.userCert == undefined || this.userCert == null) {
          this.$vux.toast.text("请输入员工身份证号码", "middle");
          return;
        } else if (!reg2.test(this.userCert)) {
          this.$vux.toast.text("请输入正确的身份证号，最后一位是字母时要大写", "middle");
          return;
        }
        if (this.nation == "" || this.nation == undefined || this.nation == null) {
          this.$vux.toast.text("请输入民族", "middle");
          return;
        } else if (!reg1.test(this.nation)) {
          this.$vux.toast.text("输入的民族必须为中文", "middle");
          return;
        }
        return true;
      },
      continueImport() {
        if (this.checkNameAndCertNum(this.userName, this.userCert)) {
          this.$vux.loading.show({
            text: '加载中',
          });
          let time = (new Date()).getTime();
          let url = baseUrl + "/resident/insert_daily_report?timestamp=" + time;
          let param = {"sgin": this.userSign, "timestamp": time};
          let signature = this.$signature(url, param);

          let data = {
            "userName": this.userName,
            "userCardNumber": this.userCert,
            "nation": this.nation
          };
          this.axios.post(baseUrl + "/resident/insert_daily_report?sgin=" + this.userSign + "&auth=" + signature + "&timestamp=" + time, data).then((res) => {
            let resultObj = res.data;
            this.$vux.loading.hide();
            this.$refs.inputImg.value = '';

            if (resultObj.code == 0) {
              if (resultObj.data == 1) {
                this.$vux.toast.text("员工录入成功~", "middle");
                this.userName = "";
                this.userCert = "";
                this.nation = "";
              } else {
                this.$vux.toast.text("员工录入失败，请重试", "middle");
              }
            } else {
              this.modalVal = true;
              this.content = resultObj.msg;
            }
          }).catch(() => {
            this.$vux.loading.hide();
            this.$vux.toast.text("网络异常", "middle");
          });
        }
      },
      completeImport() {
        if (this.checkNameAndCertNum(this.userName, this.userCert)) {
          let time = (new Date()).getTime();
          let url = baseUrl + "/resident/insert_daily_report?timestamp=" + time;
          let param = {"sgin": this.userSign, "timestamp": time};
          let signature = this.$signature(url, param);

          let data = {
            "userName": this.userName,
            "userCardNumber": this.userCert,
            "nation": this.nation
          };
          this.axios.post(baseUrl + "/resident/insert_daily_report?sgin=" + this.userSign + "&auth=" + signature + "&timestamp=" + time, data).then((res) => {
            let resultObj = res.data;
            this.$vux.loading.hide();
            this.$refs.inputImg.value = '';

            if (resultObj.code == 0) {
              if (resultObj.data == 1) {
                this.$vux.toast.text("员工录入成功~", "middle");
                setTimeout(() => {
                  this.$router.push("/dayreportlist");
                }, 1000);
              } else {
                this.$vux.toast.text("员工录入失败，请重试", "middle");
              }
            } else {
              this.modalVal = true;
              this.content = resultObj.msg;
            }
          }).catch(() => {
            this.$vux.loading.hide();
            this.$vux.toast.text("网络异常", "middle");
          });
        }
      }
    },
    watch: {
      showHeight() {
        if (this.docmHeight > this.showHeight) {
          this.hideBtn = false;
        } else {
          this.hideBtn = true;
        }
      }
    },
    components: {
      backpage,
      "v-dialog": dialog
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../assets/stylus/mixin.styl"

  .day-report-import-container
    wh(100%, 100%)
    background #f5f5f5
    .photo-upload-box
      display: flex
      flex-direction: column
      align-items: center
      wh(100%, 5.893rem)
      margin-bottom: 0.267rem
      background: #FFF
      .photo-box
        position: relative
        padding-top: 0.627rem
        padding-bottom: 0.467rem
        wh(4.8rem, 3.2rem)
        .pic1
          wh(100%, 100%)
        .upload-file
          position: absolute
          left: 0
          top: 0.627rem
          wh(4.8rem, 3.2rem)
          opacity: 0
          -ms-filter: 'alpha(opacity=0)'
          z-index: 100
      .tip1
        size-color(0.427rem, rgba(53, 183, 255, 1))
        padding-bottom: 0.213rem
      .tip2
        size-color(0.347rem, rgba(153, 153, 153, 1))

    .bank-real-info
      display: flex
      flex-direction: column
      .bank-real-name
        wh(100%, 1.333rem)
        background: #FFF
        display: flex
        border-bottom: 0.027rem solid #f2f2f2
        align-items: center
        justify-content: space-between
        &:last-child
          border-bottom: 0
        .title
          padding-left: 0.32rem
          size-color(0.427rem, #333333)
        .phone-con
          flex: 1
          text-align: right
          margin-right: 0.32rem
          .phone-num
            height: 0.6rem
            line-height: 0.6rem
            width: 100%;
            text-align: right
            size-color(0.427rem, #333333)
    .photo-scan-warp
      position: fixed
      top: 0
      left: 0
      right: 0
      bottom: 0
      z-index: 100
      display: flex
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.5)
      .photo-scan-box
        position: relative
        width: 9.08rem
        height: 5.92rem
        background: rgba(255, 255, 255, 1)
        border-radius: 0.107rem
        .photo-scan
          wh(100%, 100%)
      .discern-scan
        position: fixed
        bottom: 0.48rem
        text-align: center
        margin: 0 auto
        width: 92.53%
        height: 1.333rem
        line-height: 1.333rem
        background: rgba(60, 175, 255, 1)
        border-radius: 0.107rem
        font-size: 0.48rem
        color: rgba(255, 255, 255, 1)
    .day-report-import-btn
      position: absolute
      bottom: 0
      wh(100%, 1.28rem)
      display: flex
      align-items: center
      .import-end-btn
        flex: 1
        size-color(0.453rem, #666)
        height: 1.28rem
        line-height: 1.28rem
        background: #FFF
        border: 0
      .import-continue-btn
        flex: 1
        height: 1.28rem
        line-height: 1.28rem
        size-color(0.453rem, #FFF)
        background: #3CAFFF
        border: 0
</style>
